import { Component, OnInit } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { format, formatDistance, formatRelative, subDays } from 'date-fns';
import { NzModalService } from 'ng-zorro-antd/modal';

import { CommonService } from '../../../../services-common/common.service';
import { defalutImg } from '../../comm';
import { GameManageService } from '../../game-manage/game-manage.service';
import { GameOperateManageService } from '../game-operate-manage.service';

@Component({
  selector: 'app-game-operate-welfare',
  templateUrl: './game-operate-welfare.component.html',
  styleUrls: ['./game-operate-welfare.component.scss']
})
export class GameOperateWelfareComponent implements OnInit {

  fallback: string = defalutImg;
  searchOptions = [
    { type: 1, labelText: '游戏名称', valueKey: 'title', value: '' },
    {
      type: 2,
      labelText: '是否启用',
      valueKey: 'state',
      value: [],
      multiple: false,
      notTostr: false,
      selectBindKey: { key: 'value', label: 'label' },
      selectOptions: [
        {value: 0, label: '是'},
        {value: 1, label: '否'}
      ],
    }
  ];
  searchParams: any = {};

  tableParams: any = {
    loading: false,
    tableData: [],
    page: 1,
    pageSize: 20,
    total: 0
  };

  /**
   * 新增 | 编辑 Modal
   * ----------------------------------------------------------------
   */
  isVisible: boolean = false;
  submitLoading: boolean = false;
  modalItem: any = null;
  validateForm!: FormGroup;

  gameAppOptions: any = []; // 应用Options
  // 兑换码格式 0 统一兑换码 1 随机兑换码
  changeCodeOptions: any = [
    {value: 0, label: '统一兑换码'},
    {value: 1, label: '随机兑换码'}
  ];

  /**
   * 查看兑换码 Modal
   * ----------------------------------------------------------------
   */
  isCodeViewVisible = false;
  codeTableItem: any = null;
  codeTableParams: any = {
    loading: false,
    state: '',
    tableData: [],
    page: 1,
    pageSize: 20,
    total: 0
  };

  constructor(
    private msg: NzMessageService,
    private fb: FormBuilder,
    private modal: NzModalService,
    private commonService: CommonService,
    private gameManageService: GameManageService,
    private services: GameOperateManageService
  ) { }

  ngOnInit(): void {
    this.loadAppOptionsData();

    this.validateForm = this.fb.group({
      appId: ['', [Validators.required]], // 游戏ID
      codeType: ['', [Validators.required]], // 兑换码格式 0 统一兑换码 1 随机兑换码
      endTime: ['', [Validators.required]], // 有效期
      codeDetails: ['', [Validators.required]], // 兑换码详情
      code: [''], // 兑换码(统一)
      codes: [''] // 兑换码(随机)
    });
  }

  async loadAppOptionsData() {
    let params = {
      page: 1,
      pageSize: 10000
    }
    const {code, data}: any = await this.gameManageService.gameTableData(params);
    if (code === 0) {
      this.gameAppOptions = data.records || [];
    }
  }

  async loadTable() {
    let params = {
      ...this.searchParams,
      page: this.tableParams.page,
      pageSize: this.tableParams.pageSize
    }
    this.tableParams.loading = true;
    const {code, data, message}: any = await this.services.getGameWelfareListData(params);
    this.tableParams.loading = false;

    if (code === 0) {
      const {records, total} = data || {};
      this.tableParams.tableData = records || [];
      this.tableParams.total = total || 0;
    }
  }

  queryResetData(params: any) {
    this.searchParams = params;
    this.tableParams.page = 1;
    this.loadTable();
  }

  // PageIndex Change
  onPageIndexChange(index: number) {
    this.tableParams.page = index;
    this.loadTable();
  }
  // PageSize Change
  onPageSizeChange(sizeNum: number) {
    this.tableParams.page = 1;
    this.tableParams.pageSize = sizeNum;
    this.loadTable();
  }
  
  /**
   * ----------------------------------------------------------------
   * 上移 1 | 下移 0
   * ----------------------------------------------------------------
   */
  async moveItemData(item: any, type: number) {
    let params = {
      id: item.id,
      moveType: type
    }
    const {code, data, message}: any = await this.services.moveGameWelfareData(params);

    if (code === 0) {
      this.msg.success('操作成功');
      this.loadTable();
    }
  }

  /**
   * ----------------------------------------------------------------
   * 福利列表 删除 2 | 禁用 1
   * @param item 
   * @param state 1：禁用 2：删除
   * ----------------------------------------------------------------
   */
  async stateChangeItem(item: any, state: number) {
    let params = {
      id: item.id,
      state: state
    }
    const {code, data, message}: any = await this.services.updateGameWelfareData(params);

    if (code === 0) {
      this.msg.success('操作成功');
      this.loadTable();
    }
  }

  /**
   * ----------------------------------------------------------------
   * 查看兑换码 Modal
   * ----------------------------------------------------------------
   */
  showCodeViewModal(item: any) {
    if (item.codeType === 1) {
      // 随机兑换码
      this.codeTableItem = null;
      if (item) {
        this.codeTableItem = item;
      }

      this.codeTableParams.page = 1;
      this.loadCodeTable();
      this.isCodeViewVisible = true;
    } else {
      // 统一兑换码
      this.modal.create({
        nzTitle: '查看 - 统一兑换码',
        nzContent: `兑换码：<b>${item.code}</b>`,
        nzFooter: null
      });
    }
  }

  async loadCodeTable() {
    let params = {
      welfareId: this.codeTableItem.id,
      state: this.codeTableParams.state,
      page: this.codeTableParams.page,
      pageSize: this.codeTableParams.pageSize
    }
    this.codeTableParams.loading = true;
    const {code, data, message}: any = await this.services.getChangeCodeListData(params);
    this.codeTableParams.loading = false;

    if (code === 0) {
      this.codeTableParams.tableData = data.records || [];
      this.codeTableParams.total = data.total || 0;
    }
  }

  // PageIndex Change
  onCodePageIndexChange(index: number) {
    this.codeTableParams.page = index;
    this.loadCodeTable();
  }
  // PageSize Change
  onCodePageSizeChange(sizeNum: number) {
    this.codeTableParams.page = 1;
    this.codeTableParams.pageSize = sizeNum;
    this.loadCodeTable();
  }

  // 查看随机兑换码 搜索
  codeStateChange() {
    this.codeTableParams.page = 1;
    this.loadCodeTable();
  }

  // 删除兑换码
  async deleteChangeCode(item: any) {
    let params = {
      id: item.id,
      state: 2 // 2：删除
    }
    const {code, data, message}: any = await this.services.deleteChangeCodeData(params);

    if (code === 0) {
      this.msg.success('删除成功');
      this.codeTableParams.page = 1;
      this.loadCodeTable();

      this.loadTable();
    }
  }

  /**
   * ----------------------------------------------------------------
   * 新增 | 编辑
   * ----------------------------------------------------------------
   */
  showAddEditModal(item?: any) {
    this.validateForm.reset();
    this.modalItem = null;

    if (item) {
      this.modalItem = item;
      this.validateForm.patchValue({
        appId: item.appId, // 游戏ID
        codeType: item.codeType, // 兑换码格式 0 统一兑换码 1 随机兑换码
        endTime: item.endTime, // 有效期
        codeDetails: item.codeDetails, // 兑换码详情
        code: item.code || '', // 兑换码(统一)
        codes: item.codes || '' // 兑换码(随机)
      });
      this.codeTypeChange(item.codeType);
    }
    this.isVisible = true;
  }

  async submitForm() {
    if (this.validateForm.valid) {
      let params = {
        ...this.validateForm.value,
        endTime: format(new Date(this.validateForm.value.endTime), 'yyyy-MM-dd HH:mm:ss')
      }
      if (this.modalItem) {
        params.id = this.modalItem.id;
      }

      for (let key in params) {
        if (this.commonService.isEmpty(params[key])) {
          delete params[key];
        }
      }
      // return
      this.submitLoading = true;
      const {code, data, message}: any = await this.services.updateGameWelfareData(params);
      this.submitLoading = false;

      if (code === 0) {
        this.msg.success(`${!this.commonService.isEmpty(data) ? data : '操作成功'}`);
        this.isVisible = false;
        this.loadTable();
      }
    } else {
      Object.values(this.validateForm.controls).forEach(control => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({ onlySelf: true });
        }
      });
    }
  }

  // 自定义 随即兑换码验证
  mathCodeRequired = (control: any): any => {
    // 统一兑换码：非空且为新增(验证通过)
    // 随机兑换码：非空且为编辑且存在随机兑换码数量(验证通过)
    if ((!control.value && !this.modalItem) || (!control.value && this.modalItem && this.modalItem.codeQuantity == 0)) {
      return { required: true };
    }
    return {};
  }

  codeTypeChange(type: number) {
    if (type == 0) {
      // 统一兑换码
      this.validateForm.get('codes')!.clearValidators();
      this.validateForm.get('codes')!.markAsPristine();

      this.validateForm.get('code')!.setValidators(Validators.required);
      this.validateForm.get('code')!.markAsDirty();
    } else {
      // 随机兑换码
      this.validateForm.get('code')!.clearValidators();
      this.validateForm.get('code')!.markAsPristine();

      this.validateForm.get('codes')!.setValidators(this.mathCodeRequired);
      this.validateForm.get('codes')!.markAsDirty();
    } 
    this.validateForm.get('code')!.updateValueAndValidity();
    this.validateForm.get('codes')!.updateValueAndValidity();
  }

  uploadCodeTxtData = (data: any): any => {
    const {file} = data;
    const reader = new FileReader();

    reader.readAsText(file, "UTF-8");
    reader.onload = (ev) => {
      const str: any = ev.target?.result;

      let strReg: any = /[0-9a-z]/i;
      if (strReg.test(str.trim())) {
        let uploadCodeArrs = str.trim().replace(/\r\n/g, ',').split(',');
        let pushArrs = this.validateForm.get('codes')?.value ? this.validateForm.get('codes')?.value.split(',') : [];
        let repeatArrs = [];

        uploadCodeArrs.forEach((item: any) => {
          if (pushArrs.includes(item)) {
            repeatArrs.push(item);
            return
          }
          pushArrs.push(item);
        })

        this.validateForm.get('codes')?.setValue(pushArrs.join(','));
        this.msg.success(`${repeatArrs.length ? ('本次导入重复' + repeatArrs.length + '条，已自动合并') : '导入成功'}`);
      } else {
        this.msg.warning('您导入的文件内容为空，请检查');
      }
    }
  }

  // 上下移动 Disabled
  setMoveDisabled(index: number, type: number) {
    let currIndex = this.tableParams.pageSize * (this.tableParams.page - 1) + index + 1;

    if (type === 1) {
      // 上移
      if (currIndex === 1) {
        return true;
      } else {
        return false;
      }
    } else {
      // 下移
      if (currIndex === this.tableParams.total) {
        return true;
      } else {
        return false;
      }
    }
  }

  // 导入随机码数量
  computedCodeSize() {
    let arrs = !this.commonService.isEmpty(this.validateForm.value.codes) ?
                this.validateForm.value.codes.split(',') :
                [];
    return this.modalItem ? arrs.length + this.modalItem.codeQuantity : arrs.length;
  }
}
